import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import AudDialog from '@/pages/components/Aud/AudDialog';
import React, { useImperativeHandle, useRef } from 'react';
import { useState } from 'react';
import DataGrid, { Column } from 'devextreme-react/data-grid';
import { CpasIcon } from '~/public/cpas-ui';
// import DevDefaultPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup/DevPopup';
import notify from 'devextreme/ui/notify';

import { queryDgmc, queryDgsyh } from './service';
import { fjAndDgDataCode } from '@/utils';
import { Typography } from 'antd';
import ErrorEditPupop from './errorEditPupop';


const { Text } = Typography;

const ErrorBouncedChangeName: React.FC<any> = React.forwardRef((props: any, ref: any) => {
  const [visible, setVisible] = useState<boolean>(false);
  const diaParams = useRef<AudDialogShowParams & any>();

  const ErrorEditPupopRef = useRef<any>();

  const [dataParam, setDataParam] = useState<any>([]);
  const [dataType, setDataType] = useState<any>('');
  const [tempDataField, setTempDataField] = useState<any>('dgName');


  // const [open, setOpen] = useState(false);

  // const [openForm, setOpenForm] = useState<any>({
  //   itemName: false,
  //   itemSyh: false
  // });



  useImperativeHandle(ref, () => ({
    show: async (params: AudDialogShowParams) => {
      diaParams.current = params;
      setDataParam(diaParams.current?.args.data);
      setDataType(params?.args.pupopType);

      setTempDataField(params?.args.pupopType === 'dg' ? 'dgName' : 'fj')
      setVisible(true);
    },
    close: () => {
      setVisible(false);
    },
  }));


  // 判断并找出 tempNameArr 中的重复元素
  function findDuplicates(arr: any[]): any[] {
    const countMap = new Map<any, number>();
    arr.forEach(item => {
      countMap.set(item, (countMap.get(item) || 0) + 1);
    });
    return Array.from(countMap).filter(([item, count]) => count > 1).map(([item, count]) => item);
  }

  return (
    <>
      <div>
        <AudDialog
          ref={ref}
          visible={visible}
          title="错误信息列表"
          minWidth={500}
          width={800}
          height={500}
          {...props}
          showCancelButton={true}
          showOkButton={true}
          onOK={() => {
            let tempData: any = [];
            if (diaParams.current?.args.pupopType === 'fj') {
              const changeData = dataParam.filter((item: any) => item.codeEdit);
              const rNames = changeData.map((itemMap: any) => itemMap.fj);
              const rSourceFile = changeData.map((itemMap: any) => itemMap.sourceFile);
              tempData = [rNames, rSourceFile];
              // console.log('@@@ fj tempData', tempData);
            } else {
              if (diaParams.current?.args.valueSource === 'payload') {

                let tempNameArr: any[] = [];
                let tempSyhArr: any[] = [];
                dataParam.forEach((item: any) => {
                  item.errors.forEach((itemError: any) => {
                    if (itemError.codeEdit) {
                      if (itemError.code === '010') {
                        tempSyhArr.push(itemError.payload.DGSYH);
                      } else {
                        tempNameArr.push(itemError.payload.DGMC);
                      }
                    }
                  });
                });

                const duplicatesInTempNameArr = findDuplicates(tempNameArr);
                const duplicatesInTempSyhArr = findDuplicates(tempSyhArr);
                if (duplicatesInTempNameArr.length > 0 || duplicatesInTempSyhArr.length > 0) {
                  notify('存在重复数据，请修改后再提交', 'error', 3000);
                  return;
                }

                let tempNameS: any[] = [];
                let tempSyhS: any[] = [];
                dataParam.forEach((item: any) => {
                  const errorsArr = item.errors;
                  if (errorsArr.length === 1) {
                    const itemError = errorsArr[0];
                    if (itemError.codeEdit) {
                      if (itemError.code === '010') {
                        tempSyhS.push(itemError.payload.DGSYH);
                        tempNameS.push(null);
                      } else {
                        tempNameS.push(itemError.payload.DGMC);
                        tempSyhS.push(null);
                      }
                    }
                  } else if (errorsArr.length === 2) {
                    errorsArr.forEach((itemError: any) => {
                      if (itemError.codeEdit) {
                        if (itemError.code === '010') {
                          tempSyhS.push(itemError.payload.DGSYH);
                        } else {
                          tempNameS.push(itemError.payload.DGMC);
                        }
                      }
                    });
                  }
                });
                tempData = [tempNameS, tempSyhS];
              } else {
                let tempNameArr: any[] = [];
                let tempSyhArr: any[] = [];
                dataParam.forEach((item: any) => {
                  item.errors.forEach((itemError: any) => {
                    if (itemError.codeEdit) {
                      if (itemError.code === '010') {
                        tempSyhArr.push(itemError[dataType]);
                      } else {
                        tempNameArr.push(itemError[dataType]);
                      }
                    }
                  });
                });

                const duplicatesInTempNameArr = findDuplicates(tempNameArr);
                const duplicatesInTempSyhArr = findDuplicates(tempSyhArr);
                if (duplicatesInTempNameArr.length > 0 || duplicatesInTempSyhArr.length > 0) {
                  notify('存在重复数据，请修改后再提交', 'error', 3000);
                  return;
                }
                dataParam.forEach((item: any) => {
                  let tempObj = {
                    filePath: item.sf,
                    dgsyhs: null,
                    dgmcs: null,
                  }
                  item.errors.forEach((itemError: any) => {
                    if (itemError.codeEdit) {
                      if (itemError.code === '010') {
                        tempObj = {
                          ...tempObj,
                          dgsyhs: itemError[dataType]
                        }
                      } else {
                        tempObj = {
                          ...tempObj,
                          dgmcs: itemError[dataType]
                        }
                      }
                    }
                  })
                  tempData.push(tempObj);
                });
              }
            }
            console.log(tempData, 'tempData @@@');
            if (diaParams.current?.okCallback) {
              // console.log(tempData, 'tempData @@@');
              diaParams.current?.okCallback(tempData);
            }
            setVisible(false);
          }}
          onCancel={() => {
            setVisible(false);
            diaParams.current?.cancelCallback();
          }}
          onHiding={() => {
            setVisible(false);
            diaParams.current?.cancelCallback();
          }}
        >
          <DataGrid
            dataSource={dataParam}
            allowColumnReordering={true}
            allowColumnResizing={true}
            showRowLines={true}
            keyExpr='itemKey'
            showColumnLines={true}
            showBorders={true}
            columnResizingMode="widget"
            hoverStateEnabled={true}
            scrolling={{
              mode: 'standard',
              useNative: 'auto',
            }}
            height="100%"
          >
            <Column
              caption="名称"
              dataField={tempDataField}
              width={280} />
            <Column
              caption="原因"
              cellRender={(rowData: any) => {
                let tempStringA = '';
                const { data } = rowData;
                if (dataType === 'dg') {
                  data.errors.forEach((element: any) => {
                    tempStringA += `${element.msg};`;
                  });
                } else {
                  tempStringA = data.msg;
                }

                return (<Text style={{ width: 'calc(100% - 10px)' }} ellipsis={{ tooltip: tempStringA }}>
                  {tempStringA}
                </Text>);
              }}
            />
            <Column
              alignment='center'
              caption='操作'
              allowResizing={false}
              width={50}
              fixed={true}
              fixedPosition='right'
              cellRender={(rowData) => {
                const { data } = rowData;
                if (dataType === 'dg') {
                  const resFilter = data.errors.filter((item: any) => {
                    return item.code === '010' || item.code === '009'
                  });
                  if (resFilter.length === 0) {
                    return '';
                  }
                  // console.log('@@@rowData', data);
                  return <CpasIcon type={"icon-rename-copy"}
                    onClick={() => {
                      let tempFileSyh = '';
                      let tempFileName = '';
                      if (diaParams.current?.args.valueSource === 'payload') {
                        resFilter.forEach((element: any) => {
                          if (element.code === '010') {
                            tempFileSyh = element.payload.DGSYH;
                          } else if (element.code === '009') {
                            tempFileName = element.payload.DGMC;
                          }
                        });
                      } else {
                        resFilter.forEach((element: any) => {
                          if (element.code === '010') {
                            tempFileSyh = element.dg;
                          } else if (element.code === '009') {
                            tempFileName = element.dg;
                          }
                        });
                      }

                      ErrorEditPupopRef.current.show({
                        tempFileName,
                        tempFileSyh,
                        dbname: diaParams.current?.args.dbname,
                        dgnd: diaParams.current?.args?.dgnd ?? '',
                        itemName: tempFileName !== '',
                        itemSyh: tempFileSyh !== '',
                        itemKey: data.itemKey,
                        pupopType: diaParams.current?.args.pupopType
                      }, {
                        okCallback: async (v: any) => {
                          // console.log(v, '@@@');

                          if (diaParams.current?.args.valueSource === 'payload') {
                            setDataParam((oldData: any) => {
                              const newData = [...oldData];
                              newData.forEach((item) => {
                                if (item.itemKey === v.itemKey) {
                                  item.errors.forEach((errorItem: any) => {
                                    if (errorItem.code === '010') {
                                      if (errorItem.payload.DGSYH !== v.fileSyh) {
                                        errorItem.msg = errorItem.msg + '【已修改】';
                                        errorItem.codeEdit = true;
                                        errorItem.payload.DGSYH = v.fileSyh;
                                      }
                                    } else if (errorItem.code === '009') {
                                      if (errorItem.payload.DGMC !== v.fileName) {
                                        errorItem.msg = errorItem.msg + '【已修改】';
                                        errorItem.codeEdit = true;
                                        errorItem.payload.DGMC = v.fileName;
                                      }
                                    }
                                  });
                                  return item;
                                }
                              });
                              return newData;
                            })

                          } else {
                            setDataParam((oldData: any) => {
                              const newData = [...oldData];
                              newData.forEach((item) => {
                                if (item.itemKey === v.itemKey) {
                                  item.errors.forEach((errorItem: any) => {
                                    if (errorItem.code === '010') {
                                      if (errorItem.dg !== v.fileSyh) {
                                        errorItem.msg = errorItem.msg + '【已修改】';
                                        errorItem.codeEdit = true;
                                        errorItem.dg = v.fileSyh;
                                      }
                                    } else if (errorItem.code === '009') {
                                      if (errorItem.dg !== v.fileName) {
                                        errorItem.msg = errorItem.msg + '【已修改】';
                                        errorItem.codeEdit = true;
                                        errorItem.dg = v.fileName;
                                      }
                                    }
                                  });
                                  item.dgName = `${v.fileSyh ? '（' + v.fileSyh + '）' : ''}${v.fileName}`;
                                  return item;
                                }
                              });
                              return newData;
                            })
                          }
                        },
                      });
                    }}
                  />
                } else {
                  return <CpasIcon type={"icon-rename-copy"}
                    onClick={() => {
                      const tempFileName = data.fj;
                      ErrorEditPupopRef.current.show({
                        tempFileName,
                        dbname: diaParams.current?.args.dbname,
                        dgnd: diaParams.current?.args?.dgnd ?? '',
                        itemName: tempFileName,
                        itemKey: data.itemKey,
                        pupopType: diaParams.current?.args.pupopType
                      }, {
                        okCallback: async (v: any) => {
                          // console.log(v, '@@@');
                          setDataParam((oldData: any) => {
                            const newData = [...oldData];
                            newData.forEach((item) => {
                              if (item.itemKey === v.itemKey) {
                                item.codeEdit = true;
                                item.msg = item.msg + '【已修改】';
                                item.fj = v.fileName;
                                return item;
                              }
                            });
                            return newData;
                          })

                        },
                      });
                    }}
                  />
                }

              }}
            />
          </DataGrid>
        </AudDialog >

        <ErrorEditPupop ref={ErrorEditPupopRef} />
      </div >
    </>
  );
});

export default ErrorBouncedChangeName;
